package com.tchintech.pay.view.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.tchintech.pay.R;
import com.tchintech.pay.delegate.fragment.MyMessageFragmentDelegate;
import com.tchintech.pay.frame.presenter.FragmentPresenter;
import com.tchintech.pay.model.entity.GradesConstan;
import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.model.entity.Version;
import com.tchintech.pay.net.DownLoadManager;
import com.tchintech.pay.net.OkhttpClientTest;
import com.tchintech.pay.utils.AppConst;
import com.tchintech.pay.utils.AppTool;
import com.tchintech.pay.utils.UserState;
import com.tchintech.pay.view.activity.CardActivity;
import com.tchintech.pay.view.activity.ChangePwActivity;
import com.tchintech.pay.view.activity.LoginActivity;
import com.tchintech.pay.view.activity.PayDetailActivity;
import com.tchintech.pay.view.activity.QuickPayOneActivity;
import com.tchintech.pay.view.activity.QuickPaytwoActivity;
import com.tchintech.pay.view.activity.ShoppingunitActivity;
import com.tchintech.pay.widget.DialogWiget;

import java.io.File;
import java.util.HashMap;

/**
 * Created by Administrator on 2017/7/11 0011.
 */

public class MyMessageFragment extends FragmentPresenter<MyMessageFragmentDelegate> implements View.OnClickListener, UserState {
    protected Intent intent = new Intent();
    private TextView tv_name, tv_tele, tv_grades;
    private DialogWiget dialog = new DialogWiget();
    protected HashMap<String, String> map;
    private String urlUpdata = "Version.update";
    private Handler handler;


    @Override
    protected void initView() {
        super.initView();
        viewDelegate.setOnClickListener(this, R.id.rel_logout, R.id.real_card, R.id.real_change, R.id.real_up, R.id.real_code, R.id.real_tenant, R.id.real_bill);
        setListener();
        handler();
        //设置当前用户等级
        tv_grades = viewDelegate.getTextView(R.id.tv_grades);
        tv_grades.setText(GradesConstan.getGrades(AppConst.getUser().getGradesid()) + "用户");
    }

    private void setListener() {
        dialog.setOnQueryOkListener(new DialogWiget.OnQueryOk() {
            @Override
            public void onQueryOkClick(View v) {
                logout();
            }
        });


    }

    private void handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                hideProgressDialog();
                switch (msg.what) {
                    case HttpCode.update:
                        try {
                            Version version = getGson().fromJson(msg.obj.toString(), Version.class);
                            if (version.getRet().equals("0")) {
                                showUpdataDialog("0", version.getMsg());
                            } else if (version.getRet().equals("2")) {
                                showUpdataDialog("2", version.getMsg());
                            } else {
                                //不需要更新，直接登录
                                showMsg("当前已是最新版本");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showMsg("未知的错误");
                        }
                        break;
                }
            }
        };
    }

    @Override
    protected void initData() {
        super.initData();
        tv_name = viewDelegate.getTextView(R.id.tv_name);
        tv_tele = viewDelegate.getTextView(R.id.tv_tele);
        tv_name.setText(AppConst.getUser().getUsername());
        tv_tele.setText(AppConst.getUser().getPhone());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        /*    case R.id.line_message:
                showMsg("消息");
                intent = new Intent(getActivity(), MessageActivity.class);
                startActivity(intent);
                break;
            case R.id.line_auth:
                showMsg("实名认证");
                break;*/
            /*case R.id.real_tenant:
               // intent = new Intent(getActivity(), QuickPayOneActivity.class);
                intent = new Intent(getActivity(), QuickPaytwoActivity.class);
                startActivity(intent);
                break;*/
            case R.id.real_bill:
                //我的账单
                intent.setClass(getActivity(), PayDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.real_change:
                //修改密码
                intent.setClass(getActivity(), ChangePwActivity.class);
                startActivity(intent);
                break;
            case R.id.real_up:
                //检查更新
                updata();
                break;
            case R.id.real_card:
                intent.setClass(getActivity(), CardActivity.class);
                intent.putExtra("state", "1");
                intent.putExtra("channel_name", "ALL");
                startActivity(intent);
                break;
            case R.id.rel_logout:
                //注销登录
                dialog.showCustomMessageQuery(getActivity(), "提示", "是否注销当前账号？");
                dialog.obj = null;
                break;
            default:
                showMsg("正在开发，敬请期待");
                break;
        }
    }

    /**
     * 检查更新
     */
    private void updata() {
        showProgressDialog("", "加载中，请稍后...");
        map = new HashMap<String, String>();
        int viscode = AppTool.getVersionCode(getActivity().getApplicationContext());
        map.put("version_num", viscode + "");
        new OkhttpClientTest().path(getActivity(), handler, urlUpdata, map, HttpCode.update);
    }

    /**
     * 弹出更新对话框
     */
    public void showUpdataDialog(final String type, String content) {
        //获取手机型号
        final String model = android.os.Build.MODEL;
        if (model.contains("POS")) {
            dialog.showCustomMessageQuery(getActivity(), "应用更新", "请到应用市场更新");
        } else {
            dialog.showCustomMessageQuery(getActivity(), "应用更新", content);
        }
        dialog.setOnQueryOkListener(new DialogWiget.OnQueryOk() {

            @Override
            public void onQueryOkClick(View v) {
                System.out.println("点击确定按钮");
                if (!model.contains("POS")) {
                    downLoadApk();
                }
            }
        });
        dialog.setOnQueryCancelListener(new DialogWiget.OnQueryCancel() {

            @Override
            public void onQueryCancel(View v) {
                //强制更新点否 推出登录
                //0 更新但不强制  1 不更新   2 强制更新
                //其实这里不需要这个判断，因为已经进入软件了不可能说在让你强制更新
            }
        });
    }


    private ProgressDialog pd;
    protected boolean run = true;
    //服务器下载地址
    //固定地址 无需更改
    private String httpurl = "http://117.34.105.60/qzn.apk";

    /**
     * 下载apk
     */
    public void downLoadApk() {
        pd = new ProgressDialog(getActivity());
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage("正在下载更新");
        pd.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                run = false;
                // 断开DownLoadManager网络连接
                // 结束
                getActivity().finish();
            }
        });
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = DownLoadManager.getFileFromServer(httpurl, pd);
                    System.out.println("下载文件" + file);
                    sleep(50);
                    if (run) {
                        AppTool.installApk(file);
                    }
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = HttpCode.DOWN_ERROR;
                    handler.sendMessage(msg);
                }
            }
        }.start();
    }


    /**
     * 注销登录
     */
    private void logout() {
        //清空帐号存储
        SharedPreferences prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.commit();
        intent.setClass(getActivity(), LoginActivity.class);
        startActivity(intent);
        getActivity().finish();

    }

    @Override
    protected Class<MyMessageFragmentDelegate> getDelegateClass() {
        return MyMessageFragmentDelegate.class;
    }
}
